<?php

/**
 * @author CHUN Dany <chundany@gmail.com>
 */
class Mod_Shop extends CI_Model
{ 
  public function getShop($start, $num)
  {
    $this->db->select('*')
        ->from(table('shop'))
        ->order_by(field('updatedAt'), 'DESC');

    $this->db->limit($num, $start);

    return $this->db->get();
  }
  
  public function getShopNum()
  {
    $objDb = $this->getAllShop();
    return $objDb->num_rows();
  }
  
  public function getAllShop() {
    $this->db->select('*')
        ->from(table('shop'))
        ->order_by(field('updatedAt'), 'DESC');

    return $this->db->get();
  }
  
  public function getShopById($id)
  {
    $this->db->select('*')
        ->from(table('shop'))
        ->order_by(field('updatedAt'), 'DESC')
        ->where(field('id'), $id);

    $result = $this->db->get();

    return $result->row_array();
  }
  
  public function insert($image = NULL)
  {
    $data = array(
      field('name')       => $this->input->post('name'),
      field('flag')       => strtolower($this->input->post('flag')),
      field('image')      => $image,
      field('description')=> $this->input->post('description')
    );
    
    $this->db->insert(table('shop'), $data); 
    return $this->db->affected_rows();
  }
  
  public function update($id, $image = NULL)
  {
    $data = array(
      field('name')       => $this->input->post('name'),
      field('flag')       => strtolower($this->input->post('flag')),
      field('image')      => $image,
      field('description')=> $this->input->post('description')
    );
    $this->db->set(field('updatedAt'), 'NOW()', FALSE);
    
    if(empty($image)) unset($data[field('image')]);

    $this->db->where(field('id'),$id);
    $this->db->update(table('shop'), $data);

    return $this->db->affected_rows();
  }
  
  public function delete($id)
  {
    $this->db->set(field('deletedAt'), 'NOW()', FALSE);
    $this->db->where(field('id'), $id);
    $this->db->update(table('shop'));

    return $this->db->affected_rows();
  }
}